$(function () {
  $("#loginBox a").on("click", () => {
    $("#loginBox").hide();
    $("#registerBox").show();
  });
  $("#registerBox a").on("click", () => {
    $("#loginBox").show();
    $("#registerBox").hide();
  });

  //需求2:自定义区域校验规则
  let form = layui.form;
  //verify()的值是一个对象
  form.verify({
    //属性是规则名称,值可以是数组或者函数
    pwd: [/^[\S]{6,15}$/, "密码的长度为6-15个字符,且不能为空格"],
    repwd: function (value) {
      //规则添加给谁,value就是谁的值
      let pwd = $("#registerBox [name=password]").val();
      console.log(pwd);
      if (value !== pwd) {
        return "密码不一致";
      }
    },
  });

  //需求3:注册axios
  let layer = layui.layer;
  $("#form-reg").on("submit", (e) => {
    e.preventDefault();
    axios({
      method: "post",
      url: "/api/reguser",
      data: $("#form-reg").serialize(),
    }).then((res) => {
      console.log(res.data);
      let obj = res.data;
      if (obj.status !== 0) {
        return layer.msg(obj.message);
      }
      layer.msg(obj.message);
      //清空表单
      $("#form-reg")[0].reset();
      //切换到登陆区
      $("#registerBox a").click();
    });
  });

  //需求4:登陆,提示,跳转
  $("#form-login").on("submit", (e) => {
    e.preventDefault();
    axios({
      method: "post",
      url: "/api/login",
      data: $("#form-login").serialize(),
    }).then((res) => {
      let obj = res.data;
      if (obj.status !== 0) {
        return layer.msg(obj.message);
      }
      // layer.msg("来了,老弟", function () {
      //   location.href = "/index.html";
      //   localStorage.setItem("token", obj.token);
      // });
      layer.msg(obj.message, function () {
        //跳转
        location.href = "/index.html";
        //保存token
        localStorage.setItem("token", obj.token);
      });
    });
  });
});
